// 将products变量提升到全局作用域
let products = [
    {
        id: 1,
        name: '精选净菜套餐',
        price: 16,
        image: 'images/轮播图6.jpg',
        description: '新鲜蔬菜组合，营养均衡搭配',
        soldCount: 238
    },
    {
        id: 2,
        name: '有机蔬菜拼盘',
        price: 20,
        image: 'images/轮播图7.jpg',
        description: '多种蔬菜搭配，营养美味',
        soldCount: 456
    },
    {
        id: 3,
        name: '健康套餐A',
        price: 22,
        image: 'images/轮播图2.jpg',
        description: '适合健身人士的低脂套餐',
        soldCount: 189
    },
    {
        id: 4,
        name: '四季豆茄子组合',
        price: 18,
        image: 'images/轮播图3.jpg',
        description: '清脆四季豆配紫茄子，美味可口',
        soldCount: 367
    }
];

document.addEventListener('DOMContentLoaded', function() {
    // 初始化轮播图
    initializeSlider();
    
    // 加载产品数据
    loadProducts();
    createTechParticles();
});

function initializeSlider() {
    const slides = document.querySelectorAll('.slide');
    const sliderDots = document.querySelector('.slider-dots');
    let currentSlide = 0;
    
    // 创建轮播点
    slides.forEach((_, index) => {
        const dot = document.createElement('div');
        dot.className = `slider-dot ${index === 0 ? 'active' : ''}`;
        dot.addEventListener('click', () => goToSlide(index));
        sliderDots.appendChild(dot);
    });

    // 上一张/下一张按钮
    document.querySelector('.prev-slide').addEventListener('click', () => {
        goToSlide(currentSlide - 1);
    });

    document.querySelector('.next-slide').addEventListener('click', () => {
        goToSlide(currentSlide + 1);
    });

    function goToSlide(index) {
        if (index < 0) index = slides.length - 1;
        if (index >= slides.length) index = 0;
        
        slides.forEach(slide => slide.classList.remove('active'));
        document.querySelectorAll('.slider-dot').forEach(dot => dot.classList.remove('active'));
        
        slides[index].classList.add('active');
        document.querySelectorAll('.slider-dot')[index].classList.add('active');
        currentSlide = index;
    }

    // 自动轮播
    setInterval(() => {
        goToSlide(currentSlide + 1);
    }, 5000);
}

function loadProducts() {
    const productsGrid = document.querySelector('.products-grid');
    productsGrid.innerHTML = '';
    
    products.forEach(product => {
        const productCard = createProductCard(product);
        productsGrid.appendChild(productCard);
    });
}

function createProductCard(product) {
    const card = document.createElement('div');
    card.className = 'product-card';
    const cardContent = `
        <img src="${product.image}" alt="${product.name}">
        <div class="content">
            <h3>${product.name}</h3>
            <p class="description">${product.description}</p>
            <div class="price-row">
                <span class="price">${product.price.toFixed(2)}</span>
                <span class="sold">月售 ${product.soldCount || 0}</span>
            </div>
            <button class="add-to-cart-btn">
                <i class="fas fa-plus"></i> 加入购物车
            </button>
        </div>
    `;
    card.innerHTML = cardContent;
    
    // 直接在卡片上添加事件委托
    card.querySelector('.add-to-cart-btn').addEventListener('click', (e) => {
        e.preventDefault();
        e.stopPropagation();
        addToCart(product.id, e);
    });
    
    return card;
}

// 购物车功能
let cartItems = [];
let cartCount = 0;

function addToCart(productId, event) {
    if (!event) return;
    const product = products.find(p => p.id === productId);
    if (!product) return;

    // 创建动画元素
    const button = event.currentTarget;
    const buttonRect = button.getBoundingClientRect();
    const cartIcon = document.querySelector('.cart');
    const cartRect = cartIcon.getBoundingClientRect();
    
    const animationDot = document.createElement('div');
    animationDot.className = 'add-to-cart-animation';
    animationDot.style.left = `${buttonRect.left + buttonRect.width/2}px`;
    animationDot.style.top = `${buttonRect.top + buttonRect.height/2}px`;
    
    // 设置动画终点位置
    document.documentElement.style.setProperty('--end-x', `${cartRect.left - buttonRect.left}px`);
    document.documentElement.style.setProperty('--end-y', `${cartRect.top - buttonRect.top}px`);
    document.body.appendChild(animationDot);

    // 更新购物车
    cartItems.push(product);
    cartCount++;
    updateCartCount();
    showCartPopup();

    // 移除动画元素
    setTimeout(() => {
        document.body.removeChild(animationDot);
    }, 1000);
}

// 确保全局可访问
window.addToCart = addToCart;

function updateCartCount() {
    const cartCountElement = document.querySelector('.cart-count');
    cartCountElement.textContent = cartCount;
    cartCountElement.style.animation = 'none';
    cartCountElement.offsetHeight; // 触发重绘
    cartCountElement.style.animation = 'addToCart 0.3s ease';
}

function showCartPopup() {
    let popup = document.querySelector('.cart-popup');
    if (!popup) {
        popup = createCartPopup();
        document.body.appendChild(popup);
        
        // 添加关闭按钮事件
        popup.querySelector('.close-popup').addEventListener('click', (e) => {
            e.stopPropagation();
            closeCartPopup();
        });
        
        // 点击外部关闭
        document.addEventListener('click', function handleClickOutside(e) {
            if (!popup.contains(e.target) && !e.target.closest('.add-to-cart-btn')) {
                closeCartPopup();
            }
        });
    }
    updateCartPopup(popup);
    popup.classList.add('show');
}

function createCartPopup() {
    const popup = document.createElement('div');
    popup.className = 'cart-popup';
    popup.innerHTML = `
        <div class="cart-popup-header">
            <h3>购物车</h3>
            <span class="close-popup">&times;</span>
        </div>
        <div class="cart-items"></div>
        <div class="cart-total"></div>
    `;
    
    // 防止点击弹窗内部时关闭
    popup.addEventListener('click', (e) => {
        e.stopPropagation();
    });
    
    return popup;
}

function updateCartPopup(popup) {
    const itemsContainer = popup.querySelector('.cart-items');
    const totalElement = popup.querySelector('.cart-total');
    
    itemsContainer.innerHTML = cartItems.map((item, index) => `
        <div class="cart-item">
            <img src="${item.image}" alt="${item.name}">
            <div class="cart-item-info">
                <h4>${item.name}</h4>
                <div class="cart-item-price">${item.price.toFixed(2)}</div>
            </div>
            <button class="delete-item" data-index="${index}">×</button>
        </div>
    `).join('');

    // 添加删除按钮的事件监听
    itemsContainer.querySelectorAll('.delete-item').forEach(button => {
        button.addEventListener('click', (e) => {
            const index = parseInt(e.target.dataset.index);
            removeFromCart(index);
        });
    });

    const total = cartItems.reduce((sum, item) => sum + item.price, 0);
    totalElement.innerHTML = `
        <div class="total-price">总计: <span class="cart-item-price">${total.toFixed(2)}</span></div>
        <button class="checkout-btn">去结算</button>
    `;
}

// 添加从购物车删除商品的功能
function removeFromCart(index) {
    cartItems.splice(index, 1);
    cartCount--;
    updateCartCount();
    
    // 如果购物车为空，隐藏弹窗
    if (cartItems.length === 0) {
        document.querySelector('.cart-popup').classList.remove('show');
    } else {
        // 否则更新购物车显示
        updateCartPopup(document.querySelector('.cart-popup'));
    }
}

// 页面滚动效果
window.addEventListener('scroll', () => {
    const navbar = document.querySelector('.navbar');
    if (window.scrollY > 50) {
        navbar.classList.add('scrolled');
    } else {
        navbar.classList.remove('scrolled');
    }
});

// 添加关闭购物车弹窗的函数
function closeCartPopup() {
    const popup = document.querySelector('.cart-popup');
    if (popup) {
        popup.classList.remove('show');
        // 添加淡出动画
        popup.style.animation = 'fadeOut 0.3s ease forwards';
        // 动画结束后重置
        setTimeout(() => {
            popup.style.animation = '';
        }, 300);
    }
}

// 添加浮动粒子效果
function createTechParticles() {
    const particleCount = 20;
    for (let i = 0; i < particleCount; i++) {
        const particle = document.createElement('div');
        particle.className = 'tech-particle';
        particle.style.left = `${Math.random() * 100}vw`;
        particle.style.top = `${Math.random() * 100}vh`;
        particle.style.animationDelay = `${Math.random() * 5}s`;
        document.body.appendChild(particle);
    }
} 